using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;

namespace MCMLXVII.BackEnd.Listeners
{
    public class ConsoleSync
    {
        TcpListener server = null;
        Thread myThreadListener;
        TcpClient client = null;
        NetworkStream clientStream = null;
        bool Salir = false;

        #region B Members

        public void OnStart(Int32 port)
        {
            server = new TcpListener(System.Net.IPAddress.Any, port);
            server.Start();
            myThreadListener = new Thread(new ThreadStart(ConnectionReceiver));
            myThreadListener.Start();

        }

        private void ConnectionReceiver()
        {

            while (!Salir)
            {
                client  = server.AcceptTcpClient();
                clientStream = client.GetStream();
                while (client.Connected)
                {
                    Thread.Sleep(4000);
                }
                client.Close();
                clientStream = null;
                client = null;
            }
        }
        public void OnEnd()
        {
            Salir = false;
            try
            {
                SendData(string.Format("({0}) - Service Shutdown", System.DateTime.Now));
                if (myThreadListener.IsAlive)
                {
                    myThreadListener.Join(TimeSpan.FromMilliseconds(5000));
                    if (myThreadListener.IsAlive)
                        myThreadListener.Abort();
                }
                if (!(client == null))
                {
                    if (client.Connected)
                        client.Close();
                    client = null;
                    clientStream = null;
                }
                server.Stop();
            }
            catch 
            { 
                //nothing to do
            }
        }



        public void PublishServiceEvent(string EventInfo)
        {
            SendData(string.Format("({0}) - Event Raised ({1})\n", System.DateTime.Now, EventInfo));
        }


        public void PublishActionEvent(string ActionName, Guid ActionGid, string EventInfo)
        {
            SendData(string.Format("({0}) Action {1}, ID={2}, Info=({3})\n", System.DateTime.Now, ActionName, ActionGid, EventInfo));
        }
        

        private void SendData(string buffer)
        {
            try
            {
                if (!(clientStream == null))
                {
                    byte[] sendBuffer = Encoding.ASCII.GetBytes(buffer);
                    clientStream.Write(sendBuffer, 0, buffer.Length);
                }
            }
            catch
            { 
                //Nothing to do
            }
        }

        #endregion
    }
}
